package main

import (
	"fmt"
	"math"
	"strings"
)

func main() {
	fmt.Println(myAtoi("+1"))
}

func isDigit(elem int32) bool {
	return elem >= '0' && elem <= '9'
}

// 该题的官方解法是自动机,可以使用go语言尝试下.
func myAtoi(str string) int {
	str2 := strings.TrimSpace(str)
	res := 0
	flag := true

	for index, elem := range str2 {
		if index == 0 {
			if elem == '-' {
				flag = false
				continue
			}
			if elem == '+' {
				continue
			}

			if isDigit(elem) {
				res = int(elem - '0')
			} else {
				return 0
			}
		} else {
			if isDigit(elem) {
				r := elem - '0'
				if res > math.MaxInt32/10 || (res == math.MaxInt32/10 && r > 7) {
					if flag {
						return math.MaxInt32
					} else {
						return math.MinInt32
					}
				}
				res = res*10 + int(r)
			} else {
				break
			}
		}
	}

	if flag {
		return res
	} else {
		return -res
	}
}
